3 * File system based backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Class for a file system (FS) based file backend.
28 * All "containers" each map to a directory under the backend's base directory.
29 * For backwards-compatibility, some container paths can be set to custom paths.
30 * The wiki ID will not be used in any custom paths, so this should be avoided.
32 * Having directories with thousands of files will diminish performance.
33 * Sharding can be accomplished by using FileRepo-style hash paths.
35 * Status messages should avoid mentioning the internal FS paths.
36 * PHP warnings are assumed to be logged rather than output.
38 * @ingroup FileBackend
41 class FSFileBackend
extends FileBackendStore
{
42 protected $basePath; // string; directory holding the container directories
43 /** @var Array Map of container names to root paths */
44 protected $containerPaths = array(); // for custom container paths
45 protected $fileMode; // integer; file permission mode
46 protected $fileOwner; // string; required OS username to own files
47 protected $currentUser; // string; OS username running this script
49 protected $hadWarningErrors = array();
52 * @see FileBackendStore::__construct()
53 * Additional $config params include:
54 * - basePath : File system directory that holds containers.
55 * - containerPaths : Map of container names to custom file system directories.
56 * This should only be used for backwards-compatibility.
57 * - fileMode : Octal UNIX file permissions to use on files stored.
59 public function __construct( array $config ) {
60 parent
::__construct( $config );
62 // Remove any possible trailing slash from directories
63 if ( isset( $config['basePath'] ) ) {
64 $this->basePath
= rtrim( $config['basePath'], '/' ); // remove trailing slash
66 $this->basePath
= null; // none; containers must have explicit paths
69 if ( isset( $config['containerPaths'] ) ) {
70 $this->containerPaths
= (array)$config['containerPaths'];
71 foreach ( $this->containerPaths
as &$path ) {
72 $path = rtrim( $path, '/' ); // remove trailing slash
76 $this->fileMode
= isset( $config['fileMode'] ) ?
$config['fileMode'] : 0644;
77 if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
78 $this->fileOwner
= $config['fileOwner'];
79 $info = posix_getpwuid( posix_getuid() );
80 $this->currentUser
= $info['name']; // cache this, assuming it doesn't change
85 * @see FileBackendStore::resolveContainerPath()
86 * @param $container string
87 * @param $relStoragePath string
90 protected function resolveContainerPath( $container, $relStoragePath ) {
91 // Check that container has a root directory
92 if ( isset( $this->containerPaths
[$container] ) ||
isset( $this->basePath
) ) {
93 // Check for sane relative paths (assume the base paths are OK)
94 if ( $this->isLegalRelPath( $relStoragePath ) ) {
95 return $relStoragePath;
102 * Sanity check a relative file system path for validity
104 * @param $path string Normalized relative path
107 protected function isLegalRelPath( $path ) {
108 // Check for file names longer than 255 chars
109 if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
112 if ( wfIsWindows() ) { // NTFS
113 return !preg_match( '![:*?"<>|]!', $path );
120 * Given the short (unresolved) and full (resolved) name of
121 * a container, return the file system path of the container.
123 * @param $shortCont string
124 * @param $fullCont string
125 * @return string|null
127 protected function containerFSRoot( $shortCont, $fullCont ) {
128 if ( isset( $this->containerPaths
[$shortCont] ) ) {
129 return $this->containerPaths
[$shortCont];
130 } elseif ( isset( $this->basePath
) ) {
131 return "{$this->basePath}/{$fullCont}";
133 return null; // no container base path defined
137 * Get the absolute file system path for a storage path
139 * @param $storagePath string Storage path
140 * @return string|null
142 protected function resolveToFSPath( $storagePath ) {
143 list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
144 if ( $relPath === null ) {
145 return null; // invalid
147 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $storagePath );
148 $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
149 if ( $relPath != '' ) {
150 $fsPath .= "/{$relPath}";
156 * @see FileBackendStore::isPathUsableInternal()
159 public function isPathUsableInternal( $storagePath ) {
160 $fsPath = $this->resolveToFSPath( $storagePath );
161 if ( $fsPath === null ) {
162 return false; // invalid
164 $parentDir = dirname( $fsPath );
166 if ( file_exists( $fsPath ) ) {
167 $ok = is_file( $fsPath ) && is_writable( $fsPath );
169 $ok = is_dir( $parentDir ) && is_writable( $parentDir );
172 if ( $this->fileOwner
!== null && $this->currentUser
!== $this->fileOwner
) {
174 trigger_error( __METHOD__
. ": PHP process owner is not '{$this->fileOwner}'." );
181 * @see FileBackendStore::doStoreInternal()
184 protected function doStoreInternal( array $params ) {
185 $status = Status
::newGood();
187 $dest = $this->resolveToFSPath( $params['dst'] );
188 if ( $dest === null ) {
189 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
193 if ( file_exists( $dest ) ) {
194 if ( !empty( $params['overwrite'] ) ) {
195 $ok = unlink( $dest );
197 $status->fatal( 'backend-fail-delete', $params['dst'] );
201 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
206 if ( !empty( $params['async'] ) ) { // deferred
207 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
208 wfEscapeShellArg( $this->cleanPathSlashes( $params['src'] ) ),
209 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
211 $status->value
= new FSFileOpHandle( $this, $params, 'Store', $cmd, $dest );
212 } else { // immediate write
213 $ok = copy( $params['src'], $dest );
214 // In some cases (at least over NFS), copy() returns true when it fails
215 if ( !$ok ||
( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
216 if ( $ok ) { // PHP bug
217 unlink( $dest ); // remove broken file
218 trigger_error( __METHOD__
. ": copy() failed but returned true." );
220 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
223 $this->chmod( $dest );
230 * @see FSFileBackend::doExecuteOpHandlesInternal()
232 protected function _getResponseStore( $errors, Status
$status, array $params, $cmd ) {
233 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
234 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
235 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
240 * @see FileBackendStore::doCopyInternal()
243 protected function doCopyInternal( array $params ) {
244 $status = Status
::newGood();
246 $source = $this->resolveToFSPath( $params['src'] );
247 if ( $source === null ) {
248 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
252 $dest = $this->resolveToFSPath( $params['dst'] );
253 if ( $dest === null ) {
254 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
258 if ( file_exists( $dest ) ) {
259 if ( !empty( $params['overwrite'] ) ) {
260 $ok = unlink( $dest );
262 $status->fatal( 'backend-fail-delete', $params['dst'] );
266 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
271 if ( !empty( $params['async'] ) ) { // deferred
272 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
273 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
274 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
276 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd, $dest );
277 } else { // immediate write
278 $ok = copy( $source, $dest );
279 // In some cases (at least over NFS), copy() returns true when it fails
280 if ( !$ok ||
( filesize( $source ) !== filesize( $dest ) ) ) {
281 if ( $ok ) { // PHP bug
282 unlink( $dest ); // remove broken file
283 trigger_error( __METHOD__
. ": copy() failed but returned true." );
285 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
288 $this->chmod( $dest );
295 * @see FSFileBackend::doExecuteOpHandlesInternal()
297 protected function _getResponseCopy( $errors, Status
$status, array $params, $cmd ) {
298 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
299 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
300 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
305 * @see FileBackendStore::doMoveInternal()
308 protected function doMoveInternal( array $params ) {
309 $status = Status
::newGood();
311 $source = $this->resolveToFSPath( $params['src'] );
312 if ( $source === null ) {
313 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
317 $dest = $this->resolveToFSPath( $params['dst'] );
318 if ( $dest === null ) {
319 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
323 if ( file_exists( $dest ) ) {
324 if ( !empty( $params['overwrite'] ) ) {
325 // Windows does not support moving over existing files
326 if ( wfIsWindows() ) {
327 $ok = unlink( $dest );
329 $status->fatal( 'backend-fail-delete', $params['dst'] );
334 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
339 if ( !empty( $params['async'] ) ) { // deferred
340 $cmd = implode( ' ', array( wfIsWindows() ?
'MOVE' : 'mv',
341 wfEscapeShellArg( $this->cleanPathSlashes( $source ) ),
342 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
344 $status->value
= new FSFileOpHandle( $this, $params, 'Move', $cmd );
345 } else { // immediate write
346 $ok = rename( $source, $dest );
347 clearstatcache(); // file no longer at source
349 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
358 * @see FSFileBackend::doExecuteOpHandlesInternal()
360 protected function _getResponseMove( $errors, Status
$status, array $params, $cmd ) {
361 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
362 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
363 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
368 * @see FileBackendStore::doDeleteInternal()
371 protected function doDeleteInternal( array $params ) {
372 $status = Status
::newGood();
374 $source = $this->resolveToFSPath( $params['src'] );
375 if ( $source === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
380 if ( !is_file( $source ) ) {
381 if ( empty( $params['ignoreMissingSource'] ) ) {
382 $status->fatal( 'backend-fail-delete', $params['src'] );
384 return $status; // do nothing; either OK or bad status
387 if ( !empty( $params['async'] ) ) { // deferred
388 $cmd = implode( ' ', array( wfIsWindows() ?
'DEL' : 'unlink',
389 wfEscapeShellArg( $this->cleanPathSlashes( $source ) )
391 $status->value
= new FSFileOpHandle( $this, $params, 'Copy', $cmd );
392 } else { // immediate write
393 $ok = unlink( $source );
395 $status->fatal( 'backend-fail-delete', $params['src'] );
404 * @see FSFileBackend::doExecuteOpHandlesInternal()
406 protected function _getResponseDelete( $errors, Status
$status, array $params, $cmd ) {
407 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
408 $status->fatal( 'backend-fail-delete', $params['src'] );
409 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
414 * @see FileBackendStore::doCreateInternal()
417 protected function doCreateInternal( array $params ) {
418 $status = Status
::newGood();
420 $dest = $this->resolveToFSPath( $params['dst'] );
421 if ( $dest === null ) {
422 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
426 if ( file_exists( $dest ) ) {
427 if ( !empty( $params['overwrite'] ) ) {
428 $ok = unlink( $dest );
430 $status->fatal( 'backend-fail-delete', $params['dst'] );
434 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
439 if ( !empty( $params['async'] ) ) { // deferred
440 $tempFile = TempFSFile
::factory( 'create_', 'tmp' );
442 $status->fatal( 'backend-fail-create', $params['dst'] );
445 $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
446 if ( $bytes === false ) {
447 $status->fatal( 'backend-fail-create', $params['dst'] );
450 $cmd = implode( ' ', array( wfIsWindows() ?
'COPY' : 'cp',
451 wfEscapeShellArg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
452 wfEscapeShellArg( $this->cleanPathSlashes( $dest ) )
454 $status->value
= new FSFileOpHandle( $this, $params, 'Create', $cmd, $dest );
455 $tempFile->bind( $status->value
);
456 } else { // immediate write
457 $bytes = file_put_contents( $dest, $params['content'] );
458 if ( $bytes === false ) {
459 $status->fatal( 'backend-fail-create', $params['dst'] );
462 $this->chmod( $dest );
469 * @see FSFileBackend::doExecuteOpHandlesInternal()
471 protected function _getResponseCreate( $errors, Status
$status, array $params, $cmd ) {
472 if ( $errors !== '' && !( wfIsWindows() && $errors[0] === " " ) ) {
473 $status->fatal( 'backend-fail-create', $params['dst'] );
474 trigger_error( "$cmd\n$errors", E_USER_WARNING
); // command output
479 * @see FileBackendStore::doPrepareInternal()
482 protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
483 $status = Status
::newGood();
484 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
485 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
486 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
487 $existed = is_dir( $dir ); // already there?
488 if ( !wfMkdirParents( $dir ) ) { // make directory and its parents
489 $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
490 } elseif ( !is_writable( $dir ) ) {
491 $status->fatal( 'directoryreadonlyerror', $params['dir'] );
492 } elseif ( !is_readable( $dir ) ) {
493 $status->fatal( 'directorynotreadableerror', $params['dir'] );
495 if ( is_dir( $dir ) && !$existed ) {
496 // Respect any 'noAccess' or 'noListing' flags...
497 $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
503 * @see FileBackendStore::doSecureInternal()
506 protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
507 $status = Status
::newGood();
508 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
509 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
510 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
511 // Seed new directories with a blank index.html, to prevent crawling...
512 if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
513 $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
514 if ( $bytes === false ) {
515 $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
519 // Add a .htaccess file to the root of the container...
520 if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
521 $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
522 if ( $bytes === false ) {
523 $storeDir = "mwstore://{$this->name}/{$shortCont}";
524 $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
532 * @see FileBackendStore::doPublishInternal()
535 protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
536 $status = Status
::newGood();
537 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
538 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
539 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
540 // Unseed new directories with a blank index.html, to allow crawling...
541 if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
542 $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
543 if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
544 $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
548 // Remove the .htaccess file from the root of the container...
549 if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
550 $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
551 if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
552 $storeDir = "mwstore://{$this->name}/{$shortCont}";
553 $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
561 * @see FileBackendStore::doCleanInternal()
564 protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
565 $status = Status
::newGood();
566 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
567 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
568 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
569 wfSuppressWarnings();
570 if ( is_dir( $dir ) ) {
571 rmdir( $dir ); // remove directory if empty
578 * @see FileBackendStore::doFileExists()
579 * @return array|bool|null
581 protected function doGetFileStat( array $params ) {
582 $source = $this->resolveToFSPath( $params['src'] );
583 if ( $source === null ) {
584 return false; // invalid storage path
587 $this->trapWarnings(); // don't trust 'false' if there were errors
588 $stat = is_file( $source ) ?
stat( $source ) : false; // regular files only
589 $hadError = $this->untrapWarnings();
593 'mtime' => wfTimestamp( TS_MW
, $stat['mtime'] ),
594 'size' => $stat['size']
596 } elseif ( !$hadError ) {
597 return false; // file does not exist
599 return null; // failure
604 * @see FileBackendStore::doClearCache()
606 protected function doClearCache( array $paths = null ) {
607 clearstatcache(); // clear the PHP file stat cache
611 * @see FileBackendStore::doDirectoryExists()
614 protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
615 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
616 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
617 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
619 $this->trapWarnings(); // don't trust 'false' if there were errors
620 $exists = is_dir( $dir );
621 $hadError = $this->untrapWarnings();
623 return $hadError ?
null : $exists;
627 * @see FileBackendStore::getDirectoryListInternal()
630 public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
631 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
632 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
633 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
634 $exists = is_dir( $dir );
636 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
637 return array(); // nothing under this dir
638 } elseif ( !is_readable( $dir ) ) {
639 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
640 return null; // bad permissions?
642 return new FSFileBackendDirList( $dir, $params );
646 * @see FileBackendStore::getFileListInternal()
647 * @return array|FSFileBackendFileList|null
649 public function getFileListInternal( $fullCont, $dirRel, array $params ) {
650 list( $b, $shortCont, $r ) = FileBackend
::splitStoragePath( $params['dir'] );
651 $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
652 $dir = ( $dirRel != '' ) ?
"{$contRoot}/{$dirRel}" : $contRoot;
653 $exists = is_dir( $dir );
655 wfDebug( __METHOD__
. "() given directory does not exist: '$dir'\n" );
656 return array(); // nothing under this dir
657 } elseif ( !is_readable( $dir ) ) {
658 wfDebug( __METHOD__
. "() given directory is unreadable: '$dir'\n" );
659 return null; // bad permissions?
661 return new FSFileBackendFileList( $dir, $params );
665 * @see FileBackendStore::getLocalReference()
666 * @return FSFile|null
668 public function getLocalReference( array $params ) {
669 $source = $this->resolveToFSPath( $params['src'] );
670 if ( $source === null ) {
673 return new FSFile( $source );
677 * @see FileBackendStore::getLocalCopy()
678 * @return null|TempFSFile
680 public function getLocalCopy( array $params ) {
681 $source = $this->resolveToFSPath( $params['src'] );
682 if ( $source === null ) {
686 // Create a new temporary file with the same extension...
687 $ext = FileBackend
::extensionFromPath( $params['src'] );
688 $tmpFile = TempFSFile
::factory( wfBaseName( $source ) . '_', $ext );
692 $tmpPath = $tmpFile->getPath();
694 // Copy the source file over the temp file
695 $ok = copy( $source, $tmpPath );
700 $this->chmod( $tmpPath );
706 * @see FileBackendStore::directoriesAreVirtual()
709 protected function directoriesAreVirtual() {
714 * @see FileBackendStore::doExecuteOpHandlesInternal()
715 * @return Array List of corresponding Status objects
717 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
721 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
722 $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
726 foreach ( $pipes as $index => $pipe ) {
727 // Result will be empty on success in *NIX. On Windows,
728 // it may be something like " 1 file(s) [copied|moved].".
729 $errs[$index] = stream_get_contents( $pipe );
733 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
734 $status = Status
::newGood();
735 $function = '_getResponse' . $fileOpHandle->call
;
736 $this->$function( $errs[$index], $status, $fileOpHandle->params
, $fileOpHandle->cmd
);
737 $statuses[$index] = $status;
738 if ( $status->isOK() && $fileOpHandle->chmodPath
) {
739 $this->chmod( $fileOpHandle->chmodPath
);
743 clearstatcache(); // files changed
748 * Chmod a file, suppressing the warnings
750 * @param $path string Absolute file system path
751 * @return bool Success
753 protected function chmod( $path ) {
754 wfSuppressWarnings();
755 $ok = chmod( $path, $this->fileMode
);
762 * Return the text of an index.html file to hide directory listings
766 protected function indexHtmlPrivate() {
771 * Return the text of a .htaccess file to make a directory private
775 protected function htaccessPrivate() {
776 return "Deny from all\n";
780 * Clean up directory separators for the given OS
782 * @param $path string FS path
785 protected function cleanPathSlashes( $path ) {
786 return wfIsWindows() ?
strtr( $path, '/', '\\' ) : $path;
790 * Listen for E_WARNING errors and track whether any happen
794 protected function trapWarnings() {
795 $this->hadWarningErrors
[] = false; // push to stack
796 set_error_handler( array( $this, 'handleWarning' ), E_WARNING
);
797 return false; // invoke normal PHP error handler
801 * Stop listening for E_WARNING errors and return true if any happened
805 protected function untrapWarnings() {
806 restore_error_handler(); // restore previous handler
807 return array_pop( $this->hadWarningErrors
); // pop from stack
813 private function handleWarning() {
814 $this->hadWarningErrors
[count( $this->hadWarningErrors
) - 1] = true;
815 return true; // suppress from PHP handler
820 * @see FileBackendStoreOpHandle
822 class FSFileOpHandle
extends FileBackendStoreOpHandle
{
823 public $cmd; // string; shell command
824 public $chmodPath; // string; file to chmod
828 * @param $params array
831 * @param $chmodPath null
833 public function __construct( $backend, array $params, $call, $cmd, $chmodPath = null ) {
834 $this->backend
= $backend;
835 $this->params
= $params;
838 $this->chmodPath
= $chmodPath;
843 * Wrapper around RecursiveDirectoryIterator/DirectoryIterator that
844 * catches exception or does any custom behavoir that we may want.
845 * Do not use this class from places outside FSFileBackend.
847 * @ingroup FileBackend
849 abstract class FSFileBackendList
implements Iterator
{
852 protected $suffixStart; // integer
853 protected $pos = 0; // integer
855 protected $params = array();
858 * @param $dir string file system directory
859 * @param $params array
861 public function __construct( $dir, array $params ) {
862 $dir = realpath( $dir ); // normalize
863 $this->suffixStart
= strlen( $dir ) +
1; // size of "path/to/dir/"
864 $this->params
= $params;
867 $this->iter
= $this->initIterator( $dir );
868 } catch ( UnexpectedValueException
$e ) {
869 $this->iter
= null; // bad permissions? deleted?
874 * Return an appropriate iterator object to wrap
876 * @param $dir string file system directory
879 protected function initIterator( $dir ) {
880 if ( !empty( $this->params
['topOnly'] ) ) { // non-recursive
881 # Get an iterator that will get direct sub-nodes
882 return new DirectoryIterator( $dir );
883 } else { // recursive
884 # Get an iterator that will return leaf nodes (non-directories)
885 # RecursiveDirectoryIterator extends FilesystemIterator.
886 # FilesystemIterator::SKIP_DOTS default is inconsistent in PHP 5.3.x.
887 $flags = FilesystemIterator
::CURRENT_AS_SELF | FilesystemIterator
::SKIP_DOTS
;
888 return new RecursiveIteratorIterator(
889 new RecursiveDirectoryIterator( $dir, $flags ),
890 RecursiveIteratorIterator
::CHILD_FIRST
// include dirs
896 * @see Iterator::key()
899 public function key() {
904 * @see Iterator::current()
905 * @return string|bool String or false
907 public function current() {
908 return $this->getRelPath( $this->iter
->current()->getPathname() );
912 * @see Iterator::next()
915 public function next() {
918 $this->filterViaNext();
919 } catch ( UnexpectedValueException
$e ) {
926 * @see Iterator::rewind()
929 public function rewind() {
932 $this->iter
->rewind();
933 $this->filterViaNext();
934 } catch ( UnexpectedValueException
$e ) {
940 * @see Iterator::valid()
943 public function valid() {
944 return $this->iter
&& $this->iter
->valid();
948 * Filter out items by advancing to the next ones
950 protected function filterViaNext() {}
953 * Return only the relative path and normalize slashes to FileBackend-style.
954 * Uses the "real path" since the suffix is based upon that.
956 * @param $path string
959 protected function getRelPath( $path ) {
960 return strtr( substr( realpath( $path ), $this->suffixStart
), '\\', '/' );
964 class FSFileBackendDirList
extends FSFileBackendList
{
965 protected function filterViaNext() {
966 while ( $this->iter
->valid() ) {
967 if ( $this->iter
->current()->isDot() ||
!$this->iter
->current()->isDir() ) {
968 $this->iter
->next(); // skip non-directories and dot files
976 class FSFileBackendFileList
extends FSFileBackendList
{
977 protected function filterViaNext() {
978 while ( $this->iter
->valid() ) {
979 if ( !$this->iter
->current()->isFile() ) {
980 $this->iter
->next(); // skip non-files and dot files